package tech.aistar.wyymusicplayer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;
import tech.aistar.wyymusicplayer.pojo.Result;
import tech.aistar.wyymusicplayer.pojo.Song;
import tech.aistar.wyymusicplayer.pojo.User;
import tech.aistar.wyymusicplayer.service.SongService;
import tech.aistar.wyymusicplayer.service.UserService;
import tech.aistar.wyymusicplayer.util.JWTUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController // = @ResponseBody + @Controller
@RequestMapping("user")
public class UserController {
    //controller层调用service
    @Autowired
    private UserService userService;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping
    public Result sendCode(String email){
        User user = userService.findByEmail(email);
        if(user==null){
            userService.InsertMail(email);
            user = userService.findByEmail(email);
        }
            //return new Result("404","sorry,邮箱不存在!");

        //TODO... 发送邮箱的这段代码 - 单独使用一个线程单独去处理
        //说明邮箱是存在的
        //随机数100000~999999之间随机正整数
        //java.lang.Math  static double random();//[0.0,1.0)
        int n = (int) (Math.random()*900000+100000);
        //将int类型转换成字符串类型
        String serverCode = String.valueOf(n);

        //1. 定义一个对象,封装邮件的信息
        SimpleMailMessage msg = new SimpleMailMessage();
        //邮件的发送方,此处的邮箱应该和application-dev.yml中的配置的mail下的username保持一致
        msg.setFrom("coly666@qq.com");
        //邮件的标题
        msg.setSubject("city-login验证码");
        //邮件的正文内容
        msg.setText(serverCode);
        //邮件的接收方
        msg.setTo(email);

        //TODO... 不让发送
        //真正发送
        //mailSender.send(msg);

        //TODO... 选择将serverCode放入到服务器的内存中session空间
        //①获取session对象
        //HttpSession session = request.getSession();
        //存储的数据的格式也是key-value的形式
        //session.setAttribute("serverCode",serverCode);

        //将验证码放入到redis中,并且设置过期时间
        redisTemplate.opsForValue().set(email,serverCode,40, TimeUnit.MINUTES);

        //TODO... 验证码不要返回
        return new Result("200","发送验证码成功",serverCode);
    }

    @PostMapping
    public Result login(String email, String code) {
        User user = userService.findByEmail(email);
        if (user == null)
            return new Result("404", "邮箱不存在!");

        String serverCode = (String) redisTemplate.opsForValue().get(email);
        if (serverCode != null && serverCode.equals(code)) {
            String token = JWTUtils.geneJsonWebToken(user);

            // 检查是否为默认用户名
            boolean isDefault = userService.isDefualtUsername(user.getUsername());
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("needUpdateUsername", isDefault);

            return new Result("200", "登录成功", data);
        }
        return new Result("500", "验证码错误或已过期!");
    }
    @PostMapping("/updateUsername")
    public Result updateUsername(@RequestHeader("Authorization") String token, String newUsername) {
        // 从token中解析用户ID
        String userId = JWTUtils.validateTokenAndGetUserId(token);
        if (userId == null) {
            return new Result("401", "无效的token");
        }

        // 检查新用户名是否合法（示例逻辑）
        if (userService.usernameExists(newUsername)) {
            return new Result("500", "用户名已存在");
        }

        if (userService.updateUsername(Integer.valueOf(userId), newUsername)) {
            userService.UpdateisDefaultUsername(Integer.valueOf(userId));
            return new Result("200", "用户名更新成功");
        }
        return new Result("500", "更新失败");
    }
    @GetMapping("/info")
    public Result getUserInfo(@RequestHeader("Authorization") String token) {
        // 1. 验证并解析Token
        String userId = JWTUtils.validateTokenAndGetUserId(token);
        if (userId == null) {
            return new Result("401", "无效的token");
        }

        // 2. 获取用户信息
        User userInfo = userService.GetById(Integer.valueOf(userId));
        if (userInfo == null) {
            return new Result("404", "用户不存在");
        }


        return new Result("200", "获取成功", userInfo);
    }
}